import { Component, Input, OnInit, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
import { NzMessageService, NzModalRef, NzUploadFile } from 'ng-zorro-antd';
import { ExceptionHandler } from 'src/app/handler/exception.handler';
import { UploadService } from 'src/app/services/upload.service';
import { UploadHeaderComponent } from '../../../employee/upload-header/upload-header.component';
import Cropper from 'cropperjs';

@Component({
  selector: 'zepride-upload-background',
  templateUrl: './upload-background.component.html',
  styleUrls: ['./upload-background.component.less']
})
export class UploadBackgroundComponent implements OnInit, AfterViewInit {

  constructor(
    public uploadService: UploadService,
    private msg: NzMessageService,
    private modalRef: NzModalRef<UploadHeaderComponent>,
  ) {
  }
  @ViewChild('image') image: ElementRef<HTMLImageElement>;

  @Input() headerImg: string
  base64String = ''
  uploading = false;
  fileList = []
  type = ''
  imageChangedEvent: any = '';
  croppedImage: string;
  cropper: any;
  ngAfterViewInit() {
    this.copper();
  }
  ngOnInit(): void {
    if (!this.headerImg) {
      this.headerImg = '../../../../../../assets/images/headerImg.png'
    }
    this.croppedImage = this.headerImg
    this.base64String = this.headerImg
  }

  beforeUpload = (file: NzUploadFile): boolean => {
    this.fileList = this.fileList.concat(file);
    // console.log(this.fileList);
    this.type = file.type
    this.base64String = window.URL.createObjectURL(file);
    this.cropper.replace(this.base64String);
    return false;
  };

  // 地址转file
  dataURLtoFile(dataURI, type) {
    let binary = atob(dataURI.split(',')[1]);
    let array = [];
    for (let i = 0; i < binary.length; i++) {
      array.push(binary.charCodeAt(i));
    }
    let fileData = new Blob([new Uint8Array(array)], { type: type });
    let file = new File([fileData], `${new Date().getTime()}.png`, { type: type });
    return file
  }

  // 手动上传文件
  async handleUpload() {
    this.crop();
    let formData = new FormData();
    const file = this.dataURLtoFile(this.croppedImage, this.type)
    formData.append('file', file);
    console.log(this.fileList, formData);
    this.uploading = true;
    try {
      const { fileUrl } = await this.uploadService.upload(formData)
      this.croppedImage = fileUrl
      this.modalRef.triggerOk()
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
    this.uploading = false
  }

  // 创建画布
  copper() {
    this.cropper = new Cropper(this.image.nativeElement, {
      viewMode: 3,
      minCropBoxWidth: 480,
      // 裁剪框最小宽度
      minCropBoxHeight: 200,
      // 裁剪框最小高度
      minCanvasWidth: 500,
      initialAspectRatio: 0.5,
      autoCropArea: 1,
      // 裁剪框和画布比
      cropBoxMovable: false,
      cropBoxResizable: false
    });
  }
  // 裁剪
  crop() {
    const canvas = this.cropper.getCroppedCanvas();

    this.croppedImage = canvas.toDataURL('image/jpg');
  }
  // 放大
  big() {
    this.cropper.zoom(0.1);
  }
  // 缩小
  small() {
    this.cropper.zoom(-0.1);
  }
}
